<script lang="ts" setup>
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { MoveResourceApi, fetchResourceApi } from '@/api/Teacher/resourceApi';

// 接收父组件传递的 props
const props = defineProps<{
  visible: boolean;
  onClose: () => void;
  courseFileId: string;
  courseId: string;
  resourceId: string;
  sourceId: string;
  sourceType: string;
  fetchCourseData: (courseFileId: string | null, load: boolean, searchValue: string) => Promise<void>;
}>();

// 定义 emit 事件
const emit = defineEmits(['close']);

// 响应式数据
const levels = ref<any[]>([]); // 保存各层选择的数据
const selections = ref<string[]>([]); // 保存每一层的选择
const resourcePaths = ref<Record<string, string>>({}); // 保存 resourcePath 映射

// 获取章节数据
// 修改 fetchChildren 方法
const fetchChildren = async (parentId: string | null = null, level = 0) => {
  try {
    // 调用接口获取数据
    const response = await fetchResourceApi(parentId, ''); // 传递 parentId
    const data = response.data;

    // 只保留文件夹类型的数据
    const options = data
      .filter((item: any) => item.isFolder) // 确保只处理文件夹
      .map((item: any) => ({
        label: item.name,
        value: item.resourceId,
        resourcePath: item.resourcePath,
      }));

    // 如果没有子文件夹，清除当前层级以下的数据
    if (options.length === 0) {
      levels.value = levels.value.slice(0, level); // 清除当前层级以下数据
      return;
    }

    // 更新当前层级数据
    levels.value[level] = options;
    levels.value = levels.value.slice(0, level + 1); // 清除当前层级以下数据
    selections.value = selections.value.slice(0, level); // 清除当前层级以下选择

    // 更新 resourcePaths 映射
    resourcePaths.value = {
      ...resourcePaths.value,
      ...Object.fromEntries(options.map((item: any) => [item.value, item.resourcePath])),
    };
  }
  catch (error) {
    message.error('Failed to load child folders');
    console.error(error);
  }
};

// 监听 visible 的变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchChildren(props.courseFileId, 0); // 加载第一级数据
  }
  else {
    levels.value = [];
    selections.value = [];
  }
});

// 清除内容并关闭模态框
const handleClose = () => {
  levels.value = [];
  selections.value = [];
  emit('close'); // 触发关闭事件
};

// 选择变化时加载下一级数据
const handleSelectionChange = (value: string, level: number) => {
  selections.value[level] = value; // 更新选择
  fetchChildren(value, level + 1); // 加载下一级数据
};

// 处理确认操作
const handleConfirm = async () => {
  // 获取最后有效路径
  const selectedPath = [...selections.value] // 创建数组副本避免修改原始数组
    .reverse()
    .find(id => resourcePaths.value[id]); // 查找最后一个有效路径
  if (!selectedPath) {
    message.warning('Please select a valid chapter');
    return;
  }

  try {
    const path = resourcePaths.value[selectedPath];

    await MoveResourceApi(props.sourceId, props.sourceType, path, props.courseId);
    message.success('资源成功移动');
    handleClose();
    await props.fetchCourseData(props.resourceId, true, '');
  }
  catch (error) {
    message.error('Failed to move resource');
    console.error(error);
  }
};
</script>

<template>
  <a-modal
    title="移动到"
    :open="visible"
    :footer="null"
    @cancel="handleClose"
  >
    <template v-for="(levelOptions, level) in levels" :key="level">
      <a-select
        v-if="levelOptions && levelOptions.length > 0"
        v-model:value="selections[level]"
        placeholder="请选择"
        style="width: 100%; margin-bottom: 16px"
        @change="(value:any) => handleSelectionChange(value, level)"
      >
        <a-select-option
          v-for="option in levelOptions"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </a-select-option>
      </a-select>
    </template>

    <a-button type="primary" @click="handleConfirm">
      确定
    </a-button>
  </a-modal>
</template>
